package com.cx.mall.common.config.interceptor;


import com.cx.mall.common.enums.ResponseEnum;
import com.cx.mall.common.util.JwtUtils;

import com.cx.mall.common.util.ResponseVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Date;

public class AuthorizationInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) throws Exception {
            //获取请求头中的 token
            String token = request.getHeader("Authorization");
          //  Date expiration = JwtUtils.parseToken(token).getExpiration();
            //如果 token 为空，用户未登录。否则，如果 token 过期，登录过期，否则通过拦截并
            if(token == null){
                // 将 response 输出转换成 json 格式
                ObjectMapper objectMapper = new ObjectMapper();
                response.setContentType("application/json;charset=UTF-8");
                objectMapper.writeValue(response.getWriter(),
                        ResponseVO.fail(ResponseEnum.USER_NOT_LOGGED_IN));
                return false;
            }else if(JwtUtils.isExpired(token)){
                ObjectMapper objectMapper = new ObjectMapper();
                response.setContentType("application/json;charset=UTF-8");
                objectMapper.writeValue(response.getWriter(),
                        ResponseVO.fail(ResponseEnum.PERMISSION_TOKEN_EXPIRED));
                return false;
            }else {
                // 获取令牌中的用户信息，在登录时存储了用户的 userId
                Long id = JwtUtils.parseToken(token).get("userId", Long.class);
            }
            return true;
        }
    }

